#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''
用于获取短信状态码信息
来源：https://web.100sms.cn/returnedValue
'''


import requests
from lxml import etree
import pymysql
import time

def saveData(data):

    conn = pymysql.connect(host='10.0.0.10', user='root', password='shomop', db='shomop_sms',charset="utf8")

    cur = conn.cursor()
    count = 0
    for code, name in data.items():
        count+=1
        t = time.time()

        # print(g)

        sql = '''
        insert into  report_config(code,msg,type,createTime,updateTime,deleted)
        values(%s,%s,%s,%s,%s,%s);
       '''
        try:
            nowTime = int(round(t * 1000))
            
            type = '1'   
            if '黑名单' in name.text:
                type = '3'
            elif '关机' in name.text or '空号' in name.text or '无法接通' in name.text \
                or '不在服务区' in name.text or '手机' in name.text or '停机' in name.text \
                or '欠费' in name.text or '暂停服务' in name.text or '内存满' in name.text \
                or '限制漫游' in name.text or '终端' in name.text or '用户脱网' in name.text :
                type = '2'   
            if name.text is None:
                name.text = '空内容'
            cur.execute(sql,(code.text,name.text,type,nowTime,nowTime,'0' ))
            conn.commit()
            print(code.text + name.text +'成功')
        except  Exception as e:
            print(e)
            print(name.text) 
    print('共写入'+str(count)+'条数据')
    conn.commit()
    cur.close()
    conn.close()


url = 'https://web.100sms.cn/returnedValue'
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
print(url)
cookies = dict(JSESSIONID='4F8C477426947AD4181E0090192AC70D')
data = requests.get(url, headers=headers, cookies=cookies).text
s=etree.HTML(data)
#解析数据
# print(data)
resultcode = s.xpath("///tbody/tr/td[2]")
resulttext = s.xpath("//tbody/tr/td[3]")
# print(resultcode)
# print(resulttext)

result = zip(resultcode, resulttext)
resultDict = dict( (name,value) for name,value in result)

# saveData(resultDict)
# print(len(resultcode))
saveData(resultDict)  

for text in resulttext:
    if text.text is None:
        print('空')